<template>
	<view class="pageBg">
		<image class="w100 margin_b64" :src="img" mode="aspectFit" @error="imgError" @click.stop="previewImage"></image>
		<view v-if="isError" class="btnBox flex_c_c_c">
			<button type="default" class="refreshBtn f_32 fw_600 tc_1 margin_b16" :disabled="sending" :loading="sending" @click="getData">刷新</button>
			<text class="f_24 fw_500 tc_8">*网络塞车啦, 刷新一下吧!</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				img: '',
				refresh: false,
				sending: false,
				isError: false,
			};
		},
		onLoad(e) {
			this.getData()
		},
		methods: {
			getData() {
				/**
				 * 当后台返回图片的文件流格式时
				 * 
				 * 1. 请求时设置 responseType: 'arraybuffer' , 将数据转为类似二进制数组的格式
				 * 2. let url ='data:image/png;base64,' + uni.arrayBufferToBase64(res) , 将数据解析为img可编译的格式
				 */
				const _this = this
				if(_this.sending) {
					return
				}
				_this.sending = true
				const url = 'https://api.iyk0.com/jyu'
				_this.$api.get({
					url: url,
					loadingTip: _this.refresh ? '获取数据中...' : '',
					responseType: 'arraybuffer',
					data: {
						type: 'img'
					},
					success: res => {
						let url ='data:image/png;base64,' + uni.arrayBufferToBase64(res)
						_this.img = url
						_this.sending = false
						_this.isError = false
					},
					fail: err => {
						_this.img = 'https://cdn.pixabay.com/photo/2020/10/05/07/29/woman-5628426_960_720.jpg'
						_this.sending = false
						_this.isError = true
					}
				})
			},
			previewImage(e) {
				const _this = this
				uni.previewImage({
					urls: [_this.img]
				})
			},
			imgError(e) {
				this.img = 'https://cdn.pixabay.com/photo/2020/10/05/07/29/woman-5628426_960_720.jpg'
				_this.isError = true
			},
		},
	}
</script>

<style lang="scss" scoped>
.pageBg {
	padding-top: 32rpx;
	box-sizing: border-box;
	.btnBox {
		width: 100;
		.refreshBtn {
			width: 224rpx;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			background: #55AC6B;
			color: #FFF;
			box-shadow: 0rpx -8rpx 16rpx rgba(204, 204, 204, 0.15);
			border-radius: 44rpx;
			margin-left: 0rpx;
			margin-right: 0rpx;
		}
	}
}
</style>
